/*
 * Copyright © 2022
 * @Author: zhangxiang
 * @Date: 2022-11-24 11:20:02
 * @LastEditors: zhangxiang
 * @LastEditTime: 2023-02-13 16:20:39
 * @Description:
 *
 */

import {
  CLUSTER_PROVIDER,
  CLUSTER_PLATFORM,
  CLUSTER_ALL
} from '@/utils/constant'
import {
  getPublicTokenList,
  getPrivateAccountList
} from '@/api/cn-mgmt'

export default {
  data() {
    return {
      skipGetCloudAccount: false,
      privateUseProvider: true, // 私有云云商字段使用provider 还是 platform
      cloudProviderType: 'all',
      loadingCloudAccountName: false,
      cloudAccountNameOptions: [] // 云账户
    }
  },
  computed: {
    formCloudProvider() {
      return this.privateUseProvider ? this.form.cloudProvider : this.form.cloudPlatform
    },
    /**
     * @description: 当前选择是否公有云
     * @return {*}
     */
    isCloudProviderPublic() {
      return this.isCloudPublic(this.formCloudProvider)
    },
    /**
     * @description: 云商选项
     * @return {*}
     */
    cloudProviderOptions() {
      if (this.cloudProviderType === 'public') {
        return CLUSTER_PROVIDER
      } else if (this.cloudProviderType === 'private') {
        return CLUSTER_PLATFORM
      }
      return CLUSTER_ALL
    }
  },
  watch: {
    /**
     * @description: 监听云商
     * @return {*}
     */
    'formCloudProvider': {
      handler(newVal) {
        if (newVal && !this.skipGetCloudAccount) {
          this.form.cloudAccountName = ''
          this.getCloudAccountNameList()
        }
      },
      immediate: true
    }
  },
  methods: {
    /**
     * @description: 是否是公有云
     * @return {*}
     */
    isCloudPublic(cloudProvider) {
      const item = this.cloudProviderOptions.find((item) => {
        return item.value === cloudProvider
      })
      return item ? item.type === 'public' : true
    },
    /**
     * @description: 获取云账户
     * @return {*}
     */
    getCloudAccountNameList() {
      this.loadingCloudAccountName = true
      if (this.isCloudProviderPublic) {
        // 公有云
        getPublicTokenList({
          keyword: this.form ? this.form.cloudProvider : '',
          pageNum: 1,
          pageSize: 100
        }).then(res => {
          if (res.data) {
            this.cloudAccountNameOptions = Array.isArray(res.data.data) ? res.data.data : []
          } else {
            this.cloudAccountNameOptions = []
          }
        }).finally(() => {
          this.loadingCloudAccountName = false
        })
      } else {
        // 私有云
        getPrivateAccountList({
          keyword: this.formCloudProvider,
          pageNum: 1,
          pageSize: 100
        }).then(res => {
          if (res.data) {
            this.cloudAccountNameOptions = Array.isArray(res.data.data) ? res.data.data : []
          } else {
            this.cloudAccountNameOptions = []
          }
        }).finally(() => {
          this.loadingCloudAccountName = false
        })
      }
    }
  },
  created() {
    // this.getCloudAccountNameList()
  }
}
